using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Services;
using System.ComponentModel.DataAnnotations;

namespace Lzfy_Refund_Service.Controllers
{
    /// <summary>
    /// 退款审核工作记录控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class RefundAcctController : ControllerBase
    {
        private readonly IRefundAcctService _refundAcctService;
        private readonly ILogger<RefundAcctController> _logger;

        public RefundAcctController(
            IRefundAcctService refundAcctService,
            ILogger<RefundAcctController> logger)
        {
            _refundAcctService = refundAcctService;
            _logger = logger;
        }

        /// <summary>
        /// 根据ID获取退款审核工作记录
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <returns>退款审核工作记录</returns>
        [HttpGet("{id}")]
        public async Task<ActionResult<RefundAcctResponse>> GetById(int id)
        {
            try
            {
                var result = await _refundAcctService.GetByIdAsync(id);
                if (result == null)
                {
                    return NotFound($"未找到ID为 {id} 的退款审核工作记录");
                }
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取退款审核工作记录失败，ID: {Id}", id);
                return StatusCode(500, "服务器内部错误");
            }
        }

        /// <summary>
        /// 根据结算ID获取退款审核工作记录
        /// </summary>
        /// <param name="acctId">结算ID</param>
        /// <returns>退款审核工作记录</returns>
        [HttpGet("by-acct-id/{acctId}")]
        public async Task<ActionResult<RefundAcctResponse>> GetByAcctId(string acctId)
        {
            try
            {
                var result = await _refundAcctService.GetByAcctIdAsync(acctId);
                if (result == null)
                {
                    return NotFound($"未找到结算ID为 {acctId} 的退款审核工作记录");
                }
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据结算ID获取退款审核工作记录失败，AcctId: {AcctId}", acctId);
                return StatusCode(500, "服务器内部错误");
            }
        }

        /// <summary>
        /// 根据用户名获取退款审核工作记录列表
        /// </summary>
        /// <param name="username">用户名</param>
        /// <returns>退款审核工作记录列表</returns>
        [HttpGet("by-username/{username}")]
        public async Task<ActionResult<IEnumerable<RefundAcctResponse>>> GetByUsername(string username)
        {
            try
            {
                var result = await _refundAcctService.GetByUsernameAsync(username);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据用户名获取退款审核工作记录失败，Username: {Username}", username);
                return StatusCode(500, "服务器内部错误");
            }
        }

        /// <summary>
        /// 获取所有退款审核工作记录
        /// </summary>
        /// <returns>退款审核工作记录列表</returns>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<RefundAcctResponse>>> GetAll()
        {
            try
            {
                var result = await _refundAcctService.GetAllAsync();
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取所有退款审核工作记录失败");
                return StatusCode(500, "服务器内部错误");
            }
        }

        /// <summary>
        /// 分页获取退款审核工作记录
        /// </summary>
        /// <param name="pageNumber">页码（默认1）</param>
        /// <param name="pageSize">页大小（默认10）</param>
        /// <param name="username">用户名过滤（可选）</param>
        /// <param name="acctId">结算ID过滤（可选）</param>
        /// <param name="startDate">开始日期过滤（可选）</param>
        /// <param name="endDate">结束日期过滤（可选）</param>
        /// <returns>分页结果</returns>
        [HttpGet("paged")]
        public async Task<ActionResult<object>> GetPaged(
            [FromQuery] int pageNumber = 1,
            [FromQuery] int pageSize = 10,
            [FromQuery] string? username = null,
            [FromQuery] string? acctId = null,
            [FromQuery] DateTime? startDate = null,
            [FromQuery] DateTime? endDate = null)
        {
            try
            {
                if (pageNumber < 1) pageNumber = 1;
                if (pageSize < 1 || pageSize > 100) pageSize = 10;

                var (items, totalCount) = await _refundAcctService.GetPagedAsync(
                    pageNumber, pageSize, username, acctId, startDate, endDate);

                var result = new
                {
                    Items = items,
                    TotalCount = totalCount,
                    PageNumber = pageNumber,
                    PageSize = pageSize,
                    TotalPages = (int)Math.Ceiling((double)totalCount / pageSize)
                };

                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分页获取退款审核工作记录失败");
                return StatusCode(500, "服务器内部错误");
            }
        }

        /// <summary>
        /// 创建退款审核工作记录
        /// </summary>
        /// <param name="request">创建请求</param>
        /// <returns>创建的记录</returns>
        [HttpPost]
        public async Task<ActionResult<RefundAcctResponse>> Create([FromBody] RefundAcctCreateRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _refundAcctService.CreateAsync(request);
                return CreatedAtAction(nameof(GetById), new { id = result.Id }, result);
            }
            catch (InvalidOperationException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建退款审核工作记录失败");
                return StatusCode(500, "服务器内部错误");
            }
        }

        /// <summary>
        /// 更新退款审核工作记录
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <param name="request">更新请求</param>
        /// <returns>更新的记录</returns>
        [HttpPut("{id}")]
        public async Task<ActionResult<RefundAcctResponse>> Update(int id, [FromBody] RefundAcctUpdateRequest request)
        {
            try
            {
                if (id != request.Id)
                {
                    return BadRequest("路径中的ID与请求体中的ID不匹配");
                }

                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _refundAcctService.UpdateAsync(request);
                if (result == null)
                {
                    return NotFound($"未找到ID为 {id} 的退款审核工作记录");
                }

                return Ok(result);
            }
            catch (InvalidOperationException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新退款审核工作记录失败，ID: {Id}", id);
                return StatusCode(500, "服务器内部错误");
            }
        }

        /// <summary>
        /// 删除退款审核工作记录
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult> Delete(int id)
        {
            try
            {
                var success = await _refundAcctService.DeleteAsync(id);
                if (!success)
                {
                    return NotFound($"未找到ID为 {id} 的退款审核工作记录");
                }

                return NoContent();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除退款审核工作记录失败，ID: {Id}", id);
                return StatusCode(500, "服务器内部错误");
            }
        }

        /// <summary>
        /// 检查结算ID是否存在
        /// </summary>
        /// <param name="acctId">结算ID</param>
        /// <returns>是否存在</returns>
        [HttpGet("exists/{acctId}")]
        public async Task<ActionResult<bool>> Exists(string acctId)
        {
            try
            {
                var exists = await _refundAcctService.ExistsAsync(acctId);
                return Ok(exists);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查结算ID是否存在失败，AcctId: {AcctId}", acctId);
                return StatusCode(500, "服务器内部错误");
            }
        }

        /// <summary>
        /// 获取用户的退款审核工作统计信息
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="startDate">开始日期（可选）</param>
        /// <param name="endDate">结束日期（可选）</param>
        /// <returns>统计信息</returns>
        [HttpGet("statistics/{username}")]
        public async Task<ActionResult<object>> GetUserStatistics(
            string username,
            [FromQuery] DateTime? startDate = null,
            [FromQuery] DateTime? endDate = null)
        {
            try
            {
                var (totalCount, totalAmount) = await _refundAcctService.GetUserStatisticsAsync(
                    username, startDate, endDate);

                var result = new
                {
                    Username = username,
                    TotalCount = totalCount,
                    TotalAmount = totalAmount,
                    DateRange = new { StartDate = startDate, EndDate = endDate }
                };

                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户统计信息失败，Username: {Username}", username);
                return StatusCode(500, "服务器内部错误");
            }
        }

        /// <summary>
        /// 批量创建退款审核工作记录
        /// </summary>
        /// <param name="requests">创建请求列表</param>
        /// <returns>创建的记录列表</returns>
        [HttpPost("batch")]
        public async Task<ActionResult<IEnumerable<RefundAcctResponse>>> BatchCreate(
            [FromBody] IEnumerable<RefundAcctCreateRequest> requests)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _refundAcctService.BatchCreateAsync(requests);
                return Ok(result);
            }
            catch (InvalidOperationException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量创建退款审核工作记录失败");
                return StatusCode(500, "服务器内部错误");
            }
        }

        /// <summary>
        /// 根据日期范围获取统计报表
        /// </summary>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <returns>统计报表数据</returns>
        [HttpGet("report")]
        public async Task<ActionResult<object>> GetStatisticsReport(
            [FromQuery, Required] DateTime startDate,
            [FromQuery, Required] DateTime endDate)
        {
            try
            {
                if (startDate > endDate)
                {
                    return BadRequest("开始日期不能大于结束日期");
                }

                var result = await _refundAcctService.GetStatisticsReportAsync(startDate, endDate);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取统计报表失败");
                return StatusCode(500, "服务器内部错误");
            }
        }
    }
}